from decimal import Decimal
from typing import TypedDict
import xlwt
from datetime import date, timedelta
from xlwt import Workbook

from inventory.views.func.table_css import css1


# 生成连续日期
def generate_date_range(date_range) -> list[str]:
    start_date, end_date = date_range[0], date_range[1]
    num_days = (end_date - start_date).days + 1
    return [(start_date + timedelta(days=i)).isoformat() for i in range(num_days)]


class export_Type1(TypedDict):
    actual_date: date
    material__steel_material__name: str
    total_in: Decimal
    total_out: Decimal


# 制作出入库表，按照材质分类
def make_new_table(title: list[str], data: list[export_Type1], data_range: tuple[date, date]) -> Workbook:
    # 生成表格
    xl = xlwt.Workbook(encoding='utf-8')
    sheet1 = xl.add_sheet('Sheet1', cell_overwrite_ok=True)

    # 使用经典样式
    style, style_title = css1()

    # 确认一共需要几列
    col_num = len(title) * 2 + 1

    # 设置单元格长度
    for i in range(col_num):
        sheet1.col(i).width = 3500

    # 生成表头
    sheet1.write_merge(0, 1, 0, 0, '日期', style_title)
    k = 1
    for index, i in enumerate(title):
        sheet1.write_merge(0, 0, k, k + 1, i, style_title)
        sheet1.write(1, k, '入库', style_title)
        sheet1.write(1, k + 1, '出库', style_title)
        k += 2
    # 生成表体，写入日期
    m = 2
    date_list = generate_date_range(data_range)
    for k in date_list:
        sheet1.write(m, 0, k, style_title)
        m = m + 1
    # 起始日期
    start_date = data_range[0]
    # 开始写入数据
    for temp_data in data:
        temp1: int = (temp_data['actual_date'] - start_date).days + 2
        temp2 = 1 + title.index(temp_data['material__steel_material__name']) * 2
        if temp_data['total_in'] != 0:
            sheet1.write(temp1, temp2, temp_data['total_in'], style_title)
        if temp_data['total_out'] != 0:
            sheet1.write(temp1, temp2 + 1, temp_data['total_out'], style_title)

    return xl

